package com.example.dangerouscargodriver.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.HttpRequest;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.netmanager.Http.INetResponse;
import com.example.dangerouscargodriver.adapter.ResourceInfoAdapter;
import com.example.dangerouscargodriver.entry.ResourceInfo;
import com.example.dangerouscargodriver.entry.ResourceKeywordSearchInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int MSG_GET_RESOURCE_INFO = 1;

    private ActionBar mActionBar = null;

    public LinearLayout mBeforeSearch = null;
    public LinearLayout mAfterSearch = null;
    public ResourceInfoAdapter mViewAdapter = null;

    private HttpRequest mHttp = null;
    private HttpResponseListener mHttpListener = null;
    private MainHandler mHandler = null;

    private EditText mSearchEdit = null;
    private TextView mCancel = null;
    private TextView mSearchResult = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mBeforeSearch = findViewById(R.id.layout_before_search);
        mAfterSearch = findViewById(R.id.layout_after_search);
        mSearchResult = findViewById(R.id.tv_search_result);

        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.search_resource_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getBaseContext());
        recyclerView.setLayoutManager(layoutManager);
        mViewAdapter = new ResourceInfoAdapter();
        recyclerView.setAdapter(mViewAdapter);

        mSearchEdit = findViewById(R.id.ed_search_resource);

        mSearchEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String keyword = v.getText().toString().trim();
                mViewAdapter.clearData();
                HashMap<String, String> param = new HashMap<String, String>();
                param.put("keyword", keyword);

                mHttp.sendRequest(IHttpRequest.RequestMethod.GET_METHOD,
                        RemoteAPI.REQUEST_V1_HOME_KEYWORD_SEARCH_SOURCE_GOODS,
                        null,
                        param,
                        RemoteAPICmd.REQUEST_V1_HOME_KEYWORD_SEARCH_SOURCE_GOODS,
                        SearchActivity.class);

                // 隐藏输入法
                InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                // 显示或者隐藏输入法
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                return true;
            }
            return false;
        });
        mSearchEdit.setFocusable(true);
        mSearchEdit.setFocusableInTouchMode(true);
        mSearchEdit.requestFocus();

        mCancel = findViewById(R.id.searchCancel);
        mCancel.setOnClickListener(this);

        //初始化HTTP网络通信模块
        mHttp = HttpRequest.Instance(getBaseContext());
        mHttpListener = new HttpResponseListener();
        mHttp.attachResponseListener(mHttpListener, SearchActivity.class);
        mHttp.startUp();
        mHandler = new MainHandler(SearchActivity.this);

        mActionBar = findViewById(R.id.actionBarSearch);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.searchCancel){
            mViewAdapter.clearData();
            mBeforeSearch.setVisibility(View.VISIBLE);
            mAfterSearch.setVisibility(View.GONE);
            mSearchEdit.setText("");
        }
    }

    private class HttpResponseListener implements INetResponse {

        private static final String TAG = "HttpResponseListener";

        @Override
        public void onResponse(int actionId, String response) {
            try {
                JSONObject res = new JSONObject(response);
                Gson gson = new Gson();
                Log.d(TAG, "onResponse: " + response);

                if(actionId == RemoteAPICmd.REQUEST_V1_HOME_KEYWORD_SEARCH_SOURCE_GOODS){
                    ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                    if(responseInfo != null && responseInfo.getStatus() == 1){
                        JSONObject data = res.getJSONObject("data");
                        ResourceKeywordSearchInfo resourceSearchInfo = gson.fromJson(data.toString(), ResourceKeywordSearchInfo.class);

                        Message msg = new Message();
                        msg.what = MSG_GET_RESOURCE_INFO;
                        msg.obj = resourceSearchInfo;
                        mHandler.sendMessage(msg);
                    }
                }
                else{

                }
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onErrorResponse(int actionId, String response) {

        }
    }

    private static class MainHandler extends Handler {
        private static final String TAG = "MainHandler";
        private final WeakReference<SearchActivity> mActivity;

        MainHandler(SearchActivity activity) {
            mActivity = new WeakReference<SearchActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SearchActivity activity = mActivity.get();
            switch (msg.what){
                case MSG_GET_RESOURCE_INFO:
                {
                    ResourceKeywordSearchInfo info = (ResourceKeywordSearchInfo)msg.obj;
                    Log.d(TAG, "mSearchInfo.count: " + info.getCount());
                    Log.d(TAG, "mSearchInfo.getSource_goods: " + info.getSearchSourceGoods().size());
                    if(info != null) {
                        activity.mSearchResult.setText("共" + info.getSearchSourceGoods().size() +"个搜索结果");
                        activity.mBeforeSearch.setVisibility(View.GONE);
                        activity.mAfterSearch.setVisibility(View.VISIBLE);
                        activity.mViewAdapter.appendData(info.getSearchSourceGoods());
                    }
                }
                break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if(mHttp != null){
            mHttp.unAttachResponseListener(mHttpListener, SearchActivity.class);
        }
    }
}